//
//  XNetworkManager+Extension.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/9.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import Foundation
import YYModel

// MARK: - 微博相关
extension XNetworkManager{
    ///since_id 	false 	int64 	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///max_id 	false 	int64 	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    ///Closure use of non-escaping parameter 'complete' may allow it to escape
    func statusList(since_id:Int64,max_id:Int64,complete:@escaping ((_ list:[[String:Any]]?,_ isSuccess:Bool)->())){
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        var params:[String:Any]?
        if since_id > 0{
             params = ["since_id":since_id]
        }
        if max_id > 0
        {
            params = ["max_id":max_id-1]
        }
        tokenRequest(urlString: url, params: params) { (json, isSuccess) in
            if isSuccess{
                let array = (json as? [String:Any] ?? [:])["statuses"] as? [[String:Any]]
                
                complete(array,true)
                
                
            }else{
                complete(nil,false)
                print("失败")
            }
        }
        
    }
    func unReadStatusCount(complete:@escaping((_ count:Int)->())) {
        let url = "https://rm.api.weibo.com/2/remind/unread_count.json"
        tokenRequest(urlString: url, params: ["uid":userAccount.uid ?? 0]) { (json, isSuccess) in
            if isSuccess{
                guard let dict = json as? [String:Any],
                    let count:Int = dict["status"] as? Int
                else{
                        complete(0)
                        return
                }
                print("共\(count)条未读微博")
                complete(count)
            }else{
                complete(0)
            }
        }
    }

}
// MARK: - 用户相关
extension XNetworkManager{
    
    /// 获取token
    func loadAccessToken(code:String,complete:@escaping ((_ isSuccess : Bool)->())){
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = ["code":code,
                      "client_id":XClient_id,
                      "client_secret":XAppSecrect,
                      "grant_type":"authorization_code",
                      "redirect_uri":XRedirect_uri
                      ]

        request(method: .POST, urlString: url, params: params) {[weak self] (json, isSuccess) in
            self?.userAccount.yy_modelSet(withJSON: json ?? [:])
            
            self?.loadUserInfo(complete: { (json) in
                //1.填充模型
                self?.userAccount.yy_modelSet(with: json ?? [:])
                
                //保存到沙盒
                self?.userAccount.saveAccount()
                complete(isSuccess)
            })

            
        }
        
        
        
    }
    /// 获取用户信息
    func loadUserInfo(complete:@escaping ((_ json:[String:Any]?)->())){
        guard let uid = userAccount.uid else {
            complete(nil)
            return
        }
        let url = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        tokenRequest(urlString: url, params: params) { (json,isSuccess) in
            complete(json as? [String:Any] ?? [:])
        }
    
    }

}
